package com.yuyou.fn.tms.exception;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.tms.vo.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@ControllerAdvice
public class WebExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(WebExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult handMethodArgumentNotValidException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, MethodArgumentNotValidException ex){
        logger.error("Request Fail: {} ",httpServletRequest.getRequestURI() , ex );
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        StringBuilder sb  = new StringBuilder( );
        for(FieldError fieldError : fieldErrors ){
            if(sb.length() > 0 ){
                sb.append(";");
            }
            sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage());
        }
        return ResponseResult.fail(sb.toString());
    }

    @ExceptionHandler(BusException.class)
    @ResponseBody
    public ResponseResult handBusException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BusException ex){
        logger.error("Request Fail: {} ",httpServletRequest.getRequestURI() , ex );
        return ResponseResult.fail(ex.getMessage());
    }

    @ExceptionHandler(SignException.class)
    @ResponseBody
    public ResponseResult handSignException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, SignException ex){
        logger.error("Request Fail: {} ",httpServletRequest.getRequestURI() , ex );
        return ResponseResult.fail(ex.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResponseResult handThrowable(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Throwable ex){
        logger.error("Request Fail: {} ",httpServletRequest.getRequestURI() , ex );
        return ResponseResult.fail("服务器未知错误");
    }


}
